using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Settings : MonoBehaviour
{
    private AssetBundle asset;
    private GameObject canvasObject;

    // Start is called before the first frame update
    void Start()
    {

    }

    private void clear()
    {
        if (this.canvasObject != null)
        {
            GameObject.Destroy(this.canvasObject);
            this.asset.Unload(true);
            this.canvasObject = null;
            this.asset = null;
        }
    }

    private void OnDisable()
    {
        clear();
    }

    private void OnDestroy()
    {
        clear();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Home))
        {
            try
            {
                if (this.canvasObject != null)
                    clear();
                else
                {
                    Debug.Log($"version: {Application.unityVersion}");
                   
                    this.asset = AssetBundle.LoadFromFile("E:/Unity/Bundles/xx.cc");
                    var obj = asset.LoadAsset<GameObject>("Assets/Settings.prefab");

                    Debug.Log($"3! {obj}");
                    this.canvasObject = GameObject.Instantiate(obj);
                    this.canvasObject.SetActive(true);


                    regToggle("toggle_switch", false, p => Debug.LogError($"toggle changed: {p} "));
                    regSlider("slider_attack", 100, p => Debug.LogError($"slider changed: {p} "));
                }
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"4! {ex.Message}");
            }


            Debug.Log("get player!");

        }
    }

    void regToggle(string name, bool value, Action<bool> cb)
    {
        var toggle_switch = this.canvasObject.FindChild(p => p.name == name).FirstOrDefault();
        var toggle = toggle_switch.GetComponent<Toggle>();
        toggle.isOn = value;
        toggle.onValueChanged.AddListener(p => cb(p));
    }

    void regSlider(string name, float value, Action<float> cb)
    {
        var toggle_switch = this.canvasObject.FindChild(p => p.name == name).FirstOrDefault();
        var toggle = toggle_switch.GetComponent<Slider>();
        toggle.value = value;
        toggle.onValueChanged.AddListener(p => cb(p));
    }
}
